package com.sskj.b70.p.fragment;


import com.lzy.okgo.model.Response;
import com.lzy.okrx2.adapter.FlowableBody;
import com.sskj.b70.MyAppLication;
import com.sskj.b70.common.rxbus2.RxBus;
import com.sskj.b70.m.HttpConfig;
import com.sskj.b70.m.StockCoinBean;
import com.sskj.b70.m.bean.CoinFee;
import com.sskj.b70.m.bean.Entrust;
import com.sskj.b70.m.bean.HaiPageBean;
import com.sskj.b70.m.bean.HttpData;
import com.sskj.b70.m.bean.TransactionModel;
import com.sskj.b70.m.bean.UserCoinInfo;
import com.sskj.b70.m.bean.UserInfo;
import com.sskj.b70.m.bean.rxbus.StockCoin;
import com.sskj.b70.m.http.ExceptionUtil;
import com.sskj.b70.m.http.JsonCallBack;
import com.sskj.b70.m.http.JsonConverter;
import com.sskj.b70.p.base.BasePresenter;
import com.sskj.b70.utils.DisposUtil;
import com.sskj.b70.v.fragment.TransactionFragment;

import java.util.HashMap;
import java.util.List;

import io.reactivex.Flowable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function4;

/**
 * Created by Administrator on 2018/4/26.
 */

public class TransactionPresenter extends BasePresenter<TransactionFragment> {


    private Disposable disposable;

    /**
     * 获取股票最新数据
     *
     * @param
     * @param code 编码
     */
    public void getNewInfo(String code) {
        httpService.getProduct(code)
                .tag(this)
                .execute(new JsonCallBack<HttpData<List<StockCoinBean>>>(this) {
                    @Override
                    protected void _onSuccess(Response<HttpData<List<StockCoinBean>>> response) {
                        mView.updateNewPrice(response.body().getData().get(0).getStockProductVO());
                    }
                });
    }


    /**
     * 获取最新交易列表
     *
     * @param
     * @param code 编号
     */
    public void getEntrustList(String code) {
        if (MyAppLication.isLogin()) {
            httpService.getCoinEntrustingList(code)
                    .tag(this)
                    .execute(new JsonCallBack<HttpData<HaiPageBean<Entrust>>>() {
                        @Override
                        public void _onSuccess(Response<HttpData<HaiPageBean<Entrust>>> response) {
                            if (response.body() != null) {
                                if (response.body().getStatus() == HttpConfig.STATUS_OK) {
                                    mView.setHistory(response.body().getData().getRes());
                                }
                            }
                        }
                    });
        }

    }


    /**
     * 提交订单
     *
     * @param code          币种编号
     * @param price         委托价格 （限价必填）
     * @param num           委托数量 （限价必填）
     * @param tradeType     1买入 2卖出 （必填）
     * @param billPriceType 1市价 2限价 （必填）
     */
    public void submit(String code, String price, String num,
                       int tradeType, int billPriceType) {

        httpService.creatCoinOrder(code, price, num, tradeType, billPriceType)
                .tag(this)
                .execute(new JsonCallBack<HttpData<String>>(this) {
                    @Override
                    public void _onSuccess(Response<HttpData<String>> response) {
                        if (response.body() != null) {
                            if (response.body().getStatus() == HttpConfig.STATUS_OK) {
                                mView.submitOrderSuccess(response.body().getMsg());
                            } else {
                                mView.submitOrderFail(response.body().getMsg());
                            }
                        }

                    }
                });
    }


    /**
     * 撤销订单
     *
     * @param
     * @param order_id 订单号
     */
    public void cancelOrder(int tradeType, String order_id) {
        httpService.cancelCoinOrder(tradeType, order_id)
                .tag(this)
                .execute(new JsonCallBack<HttpData<String>>(this, 1) {
                    @Override
                    public void _onSuccess(Response<HttpData<String>> response) {
                        if (response.body() != null) {
                            if (response.body().getStatus() == HttpConfig.STATUS_OK) {
                                mView.cancelOrder(response.body().getMsg(), true);
                            } else {
                                mView.cancelOrder(response.body().getMsg(), true);
                            }
                        }
                    }

                });

    }

    public void getStockCoinByCode(String code) {
        mView.mActivity.showLoading();
        if (MyAppLication.isLogin()) {
            HashMap<String, String> feeMap = new HashMap<>();
            feeMap.put("USDT","coin_coin_deal_fee");
            feeMap.put("BTC","coin_coin_deal_fee_btc");
            feeMap.put("ETH","coin_coin_deal_fee_eth");

            Flowable<HttpData<List<StockCoinBean>>> flowCoin = httpService.getProduct(code)
                    .converter(new JsonConverter<HttpData<List<StockCoinBean>>>() {
                    })
                    .adapt(new FlowableBody<>());

            Flowable<HttpData<UserCoinInfo>> flowOneCoinInfoFront= httpService.getCoinTypeInfo(code.split("/")[0])
                    .converter(new JsonConverter<HttpData<UserCoinInfo>>() {
                    })
                    .adapt(new FlowableBody<>());

            Flowable<HttpData<UserCoinInfo>> flowOneCoinInfoBack = httpService.getCoinTypeInfo(code.split("/")[1])
                    .converter(new JsonConverter<HttpData<UserCoinInfo>>() {
                    })
                    .adapt(new FlowableBody<>());
            Flowable<HttpData<List<CoinFee>>> flowCoinFeeInfo = httpService.getCoinFee(feeMap.get(code.split("/")[1]))
                    .converter(new JsonConverter<HttpData<List<CoinFee>>>() {
                    })
                    .adapt(new FlowableBody<>());
            disposable = Flowable.zip(flowCoin, flowOneCoinInfoFront, flowOneCoinInfoBack, flowCoinFeeInfo,
                    new Function4<HttpData<List<StockCoinBean>>, HttpData<UserCoinInfo>, HttpData<UserCoinInfo>, HttpData<List<CoinFee>>, StockCoin>() {
                        @Override
                        public StockCoin apply(HttpData<List<StockCoinBean>> listHttpData, HttpData<UserCoinInfo> coinInfoFront, HttpData<UserCoinInfo> coinInfoBack, HttpData<List<CoinFee>> coinFeeHttpData) throws Exception {
                            StockCoin stockCoin = new StockCoin();
                            stockCoin.setSellPrice(listHttpData.getData().get(0).getStockProductVO().getSell() + "");
                            stockCoin.setBuyPrice(listHttpData.getData().get(0).getStockProductVO().getBuy() + "");
                            stockCoin.setName(listHttpData.getData().get(0).getName());
                            stockCoin.setTransFee(Double.valueOf(coinFeeHttpData.getData().get(0).getValue()));
                            stockCoin.setMoney(coinInfoBack.getData().getUsableFund());
                            stockCoin.setHaveNum(coinInfoFront.getData().getUsableFund());
                            stockCoin.setPrice(listHttpData.getData().get(0).getStockProductVO().getPrice());
                            return stockCoin;
                        }
                    }).subscribe(stockCoin -> {
                mView.mActivity.hideLoading();
                mView.setSockCoin(stockCoin);
            }, e -> {
                ExceptionUtil.dealException(e);
                mView.mActivity.hideLoading();
            });
        } else {
            httpService.getProduct(code)
                    .tag(this)
                    .converter(new JsonConverter<HttpData<List<StockCoinBean>>>() {
                    })
                    .adapt(new FlowableBody<>())
                    .map(listHttpData -> {
                        StockCoin stockCoin = new StockCoin();
                        stockCoin.setSellPrice(listHttpData.getData().get(0).getStockProductVO().getSell() + "");
                        stockCoin.setBuyPrice(listHttpData.getData().get(0).getStockProductVO().getBuy() + "");
                        stockCoin.setName(listHttpData.getData().get(0).getName());
                        stockCoin.setTransFee(listHttpData.getData().get(0).getDealFee());
                        stockCoin.setMoney("0");
                        stockCoin.setHaveNum(0+"");
                        stockCoin.setPrice(listHttpData.getData().get(0).getStockProductVO().getPrice());
                        return stockCoin;
                    }).subscribe(stockCoin -> {
                mView.mActivity.hideLoading();
                mView.setSockCoin(stockCoin);
            }, e -> {
                mView.mActivity.hideLoading();
                ExceptionUtil.dealException(e);

            });
        }
    }

    public void getUserInfo() {
        if (MyAppLication.isLogin()) {
            httpService.getUserInfo()
                    .tag(this)
                    .execute(new JsonCallBack<HttpData<UserInfo>>() {
                        @Override
                        public void _onSuccess(Response<HttpData<UserInfo>> response) {
                            HttpData<UserInfo> httpData = response.body();
                            if (httpData.getStatus() == HttpConfig.STATUS_OK && httpData.getData() != null) {
                                RxBus.getDefault().post(httpData.getData());
                                mView.updateWallet(httpData.getData().getWallone());
                            }
                        }
                    });
        }
    }

    public void getPankou(String code) {
        httpService.getPankou(code)
                .tag(this)
                .execute(new JsonCallBack<HttpData<TransactionModel>>() {
                    @Override
                    protected void _onSuccess(Response<HttpData<TransactionModel>> response) {
                        mView.setBuySell(response.body().getData());
                    }
                });
    }


    @Override
    public void detachView() {
        DisposUtil.close(disposable);
        super.detachView();
    }

}